package org.momo.rpc.client.impl;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.momo.rpc.circuitbreaker.impl.CircuitBreaker;
import org.momo.rpc.protocol.RpcMessage;
import org.momo.rpc.protocol.RpcRequest;
import org.momo.rpc.protocol.RpcResponse;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;


@Data
@AllArgsConstructor
public class UnprocessedRequest {

    private RpcMessage<RpcRequest> requestMessage;

    private CircuitBreaker circuitBreaker;

    private CompletableFuture<RpcMessage<RpcResponse>> resultFuture;


    private static final Map<Long, UnprocessedRequest> unprocessedQueue = new ConcurrentHashMap<>();

    public static UnprocessedRequest get(Long requestId) {
        return unprocessedQueue.get(requestId);
    }
    
    public static CompletableFuture<RpcMessage<RpcResponse>> put(Long requestId, RpcMessage<RpcRequest> request, CircuitBreaker circuitBreaker) {
        CompletableFuture<RpcMessage<RpcResponse>> resultFuture = new CompletableFuture<>();
        unprocessedQueue.put(requestId, new UnprocessedRequest(request, circuitBreaker, resultFuture));
        return resultFuture;
    }
    
    public static void remove(Long requestId) {
        unprocessedQueue.remove(requestId);
    }
}
